package com.phone.download;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.cloudtech.multidownload.MultiDownloadManager;
import com.cloudtech.multidownload.entitis.FileInfo;
import com.cloudtech.multidownload.service.DownloadService;

public class MainActivity extends Activity {

    private String TAG = "SDSIZE";
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private ListView listView;
    private List<String> urlList;
    private List<FileInfo> mFileList;
    private FileAdapter mAdapter;

    private String urlone = "http://break.cloudmobi.net/small.pdf";
    private String urltwo = "http://break.cloudmobi.net/large.pdf";
    private String urlthree = "http://s1.music.126.net/download/android/CloudMusic_3.4.1.133604_official.apk";
    private String urlfour = "http://study.163.com/pub/study-android-official.apk";
    private String urlfive = "http://cdn.mvideo.cloudmobi.net/upload-files/view?path=7e8e7a87f49e9377230d6763e5a53846";

    // /storage/emulated/0/download/
    public static final String DownloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/";

    private UIRecive mRecive;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;

        checkPermission();

        MultiDownloadManager.openDebug(true);

        listView = (ListView) findViewById(R.id.list_view);
        mFileList = new ArrayList<>();
        urlList = new ArrayList<>();

//		参数：
//		文件id/文件下载url/文件下载名/文件本地路径/下载线程个数/下载超时时间/下载失败是否自动继续尝试断点下载
//		如果设置了自动下载失败自动继续尝试断点下载，就会接受不到失败事件
        FileInfo fileInfo1 = new FileInfo(0, urlone, getfileName(urlone), DownloadPath, 3, 5, true);
        FileInfo fileInfo2 = new FileInfo(1, urltwo, getfileName(urltwo), DownloadPath, 3, 5, true);
        FileInfo fileInfo3 = new FileInfo(2, urlone, getfileName(urlthree), DownloadPath, 3, 20, true);
        FileInfo fileInfo4 = new FileInfo(3, urltwo, getfileName(urlfour), DownloadPath, 3, 20, true);
        FileInfo fileInfo5 = new FileInfo(4, urlfive, "video", DownloadPath, 3, 20, true);

        urlList.add(urlone);
        urlList.add(urltwo);
        urlList.add(urlthree);
        urlList.add(urlfour);
        urlList.add(urlfive);

        mFileList.add(fileInfo1);
        mFileList.add(fileInfo2);
        mFileList.add(fileInfo3);
        mFileList.add(fileInfo4);
        mFileList.add(fileInfo5);

        mAdapter = new FileAdapter(this, mFileList);

        listView.setAdapter(mAdapter);

        mRecive = new UIRecive();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadService.ACTION_UPDATE);
        intentFilter.addAction(DownloadService.ACTION_FINISHED);
        intentFilter.addAction(DownloadService.ACTION_START);
        registerReceiver(mRecive, intentFilter);

        findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(Intent.ACTION_VIEW);
                String filePath = DownloadPath + "TrashClear.apk";
                File file = new File(filePath);

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {

//                    openFile(file, context);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(filePath));
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {

                    intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                }
                context.startActivity(intent);

//				for (String s : urlList) {
//					String path = DownloadPath + getfileName(s);
//					Log.i("size", "onClick: path -> " + path);
//
//					double size = FileSizeUtil.getFileSize(path,3);
//					Log.i("size", "onClick: size -> " + size);
//				}
//				String path = "/storage/emulated/0/download/small.pdf";
//				File dataFile = Environment.getDataDirectory();

                // sd卡上可用空间的大小
//				while(true){
//					File sdFile =  Environment.getExternalStorageDirectory();
//					long freeSpace = sdFile.getFreeSpace();  //未分配的字节数
//
//
//					long usAble = sdFile.getUsableSpace();
//					long totalAble = sdFile.getTotalSpace();
//
//					double free = FileSizeUtil.FormetFileSize(freeSpace, 3);
//					double use = FileSizeUtil.FormetFileSize(usAble, 3);
//					double total = FileSizeUtil.FormetFileSize(totalAble, 3);
//
//					Log.i(TAG, "free --> " + free + "::use-> " + use + "::total-> " + total);
//				}

            }
        });
    }

    private void openFile(File file, Context context) {
        Intent intent = new Intent();

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,"com.android.vending");
        String type = "application/vnd.android.package-archive";
        Log.e("type",type);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", file), type);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
        }

        intent.putExtra(Intent.EXTRA_REFERRER, Uri.parse("android-app://com.android.vending"));

        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }


    public void checkPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 321);
                }
            }

        }
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mRecive);
        MultiDownloadManager.destory(this);
        super.onDestroy();
    }

    private String getfileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }


    class UIRecive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {
                // 更新进度条的时候
                int finished = MultiDownloadManager.getFileFinished(intent);
                Log.i("jw", "finished:" + finished);
                int id = MultiDownloadManager.getFileId(intent);
                mAdapter.updataProgress(id, finished);
            } else if (DownloadService.ACTION_FINISHED.equals(intent.getAction())) {
                // 下载结束的时候
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                mAdapter.updataProgress(fileInfo.getId(), 0);
                Toast.makeText(MainActivity.this, mFileList.get(fileInfo.getId()).getFileName() + "下载完成", Toast.LENGTH_SHORT).show();
            } else if (DownloadService.ACTION_START.equals(intent.getAction())) {
                //开始下载
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                Toast.makeText(MainActivity.this, mFileList.get(fileInfo.getId()).getFileName() + "开始下载", Toast.LENGTH_SHORT).show();
            } else if (DownloadService.ACTION_ERROR.equals(intent.getAction())) {
                //下载失败
                FileInfo fileInfo = MultiDownloadManager.getFileInfo(intent);
                int id = MultiDownloadManager.getFileId(intent);
                mAdapter.updateError(id);
                Toast.makeText(MainActivity.this, mFileList.get(fileInfo.getId()).getFileName() + "下载失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

}
